package transport

import (
	"sync"
)

type transportPool struct {
	fd         int
	transports *sync.Map
}

func NewTransportPool() TransportPool {
	tp := &transportPool{
		transports: &sync.Map{},
	}
	err := tp.Init()
	if err != nil {
		panic(err)
	}
	return tp
}

func (w *transportPool) Close() error {
	var err error
	w.transports.Range(func(_, value any) bool {
		tt := value.(Transport)
		if e := tt.Close(); e != nil {
			err = e
		}
		return true
	})
	return err
}

func (w *transportPool) getTransport(fd int) (Transport, bool) {
	t, exist := w.transports.Load(fd)
	return t.(Transport), exist
}

func (w transportPool) closeTransport(t Transport) {
	_ = w.Remove(t)
	_ = t.Close()
}
func (w *transportPool) WaitMessage() ([]Transport, []Transport, error) {
	ts, closedTs, err := w.waitMessage()

	for _, t := range ts {
		t.Ready()
	}

	return ts, closedTs, err
}
